<template>
  <div class="warehouse-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>仓库管理</h2>
    </div>

    <!-- 调试信息 -->
    <div v-if="debugInfo.apiStatus !== '所有数据加载完成'" class="debug-info"
      style="background: #f0f9ff; border: 1px solid #0ea5e9; padding: 10px; margin-bottom: 10px; border-radius: 4px;">
      <div style="color: #0369a1; font-weight: bold;">🔧 调试信息</div>
      <div>状态: {{ debugInfo.apiStatus }}</div>
      <div v-if="debugInfo.errorMessage">错误: {{ debugInfo.errorMessage }}</div>
      <div>数据字典大小: 分类({{ categoryMap.size }}) 类型({{ storageTypeMap.size }}) 结构({{ structureMap.size }}) 人员({{
        personMap.size }})</div>
    </div>

    <!-- 操作栏 -->
    <div class="operation-bar">
      <div class="left-operations">
        <el-button type="primary" @click="handleAdd">
          <el-icon>
            <Plus />
          </el-icon>
          新增
        </el-button>
        <el-button @click="handleExport">
          <el-icon>
            <Download />
          </el-icon>
          导出
        </el-button>
        <el-button type="warning" @click="testAllPorts">
          测试端口
        </el-button>
      </div>
      <div class="right-operations">
        <el-input v-model="searchKeyword" placeholder="请搜索仓库名称、编号或地址" class="search-input" clearable
          @input="handleSearch">
          <template #prefix>
            <el-icon>
              <Search />
            </el-icon>
          </template>
        </el-input>
        <el-button @click="toggleViewMode" class="view-toggle">
          <el-icon>
            <Grid v-if="viewMode === 'table'" />
            <List v-else />
          </el-icon>
        </el-button>
      </div>
    </div>



    <!-- 仓库列表 -->
    <div class="warehouse-list">
      <el-table v-loading="loading" :data="warehouseList" row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" class="warehouse-table">
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" width="80">
          <template #default="{ $index }">
            {{ serialNumber($index) }}
          </template>
        </el-table-column>
        <el-table-column prop="warehouseName" label="仓库名称" min-width="200">
          <template #default="{ row }">
            <div class="warehouse-name-cell">
              <el-icon v-if="row.children && row.children.length > 0">
                <Folder v-if="row.expanded" />
                <FolderOpened v-else />
              </el-icon>
              <el-icon v-else>
                <Document />
              </el-icon>
              <span>{{ row.warehouseName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="warehouseNumber" label="仓库编号" width="150" />
        <el-table-column prop="categoryName" label="仓库分类" width="120" />
        <el-table-column prop="storageTypeName" label="存储类型" width="120" />
        <el-table-column prop="structureName" label="仓库结构" width="120" />
        <el-table-column prop="isEnabled" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isEnabled ? 'success' : 'danger'" size="small">
              <el-icon v-if="row.isEnabled">
                <Check />
              </el-icon>
              <el-icon v-else>
                <Close />
              </el-icon>
              {{ row.isEnabled ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="personInChargeName" label="负责人" width="100" />
        <el-table-column prop="address" label="仓库地址" min-width="200" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              删除
            </el-button>
            <el-button type="info" link @click="handleView(row)">
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
        :page-sizes="[4, 6, 8, 10]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <!-- 新增/编辑对话框 -->
    <WarehouseDialog v-model:visible="dialogVisible" :warehouse="currentWarehouse" :mode="dialogMode"
      @success="handleDialogSuccess" />

    <!-- 详情对话框 -->
    <WarehouseDetailDialog v-model:visible="detailDialogVisible" :warehouse="currentWarehouse"
      @edit="handleEditFromDetail" @delete="handleDeleteFromDetail" />

    <!-- 根节点编辑对话框 -->
    <RootNodeDialog v-model:visible="rootNodeDialogVisible" :warehouse="currentWarehouse"
      @success="handleRootNodeSuccess" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Download, Search, Grid, List, Folder, FolderOpened, Document, Check, Close } from '@element-plus/icons-vue'
import WarehouseDialog from './components/WarehouseDialog.vue'
import WarehouseDetailDialog from './components/WarehouseDetailDialog.vue'
import RootNodeDialog from './components/RootNodeDialog.vue'
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'
import { getErrorMessage, isNetworkError } from '@/utils/error'
import {
  getWarehouseList,
  deleteWarehouse,
  getWarehouseById,
  getAllWarehouseCategories,
  getAllStorageTypes,
  getAllWarehouseStructures,
  getAllPersons
} from '@/Https/server'

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')
const viewMode = ref('table')
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const rootNodeDialogVisible = ref(false)
const dialogMode = ref<'add' | 'edit'>('add')
const currentWarehouse = ref<any>(null)

// 数据字典
const categoryMap = ref<Map<number, string>>(new Map())
const storageTypeMap = ref<Map<number, string>>(new Map())
const structureMap = ref<Map<number, string>>(new Map())
const personMap = ref<Map<number, string>>(new Map())
const warehouseList = ref<any[]>([])



// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 4,
  total: 0
})

// 计算属性
const serialNumber = computed(() => {
  return (index: number) => (pagination.currentPage - 1) * pagination.pageSize + index + 1
})

// 方法


// 测试数据字典API
const testDataDictionaryAPIs = async () => {
  const testUrls = [
    // 仓库分类
    'http://localhost:5107/api/WarehouseCategory/list',
    'http://localhost:5107/api/WarehouseCategory',
    'http://localhost:5107/api/Category/list',
    'http://localhost:5107/api/Category',
    // 存储类型
    'http://localhost:5107/api/StorageType/list',
    'http://localhost:5107/api/StorageType',
    // 仓库结构
    'http://localhost:5107/api/WarehouseStructure/list',
    'http://localhost:5107/api/WarehouseStructure',
    'http://localhost:5107/api/Structure/list',
    // 人员
    'http://localhost:5107/api/Person/list',
    'http://localhost:5107/api/Person',
    'http://localhost:5107/api/User/list',
    'http://localhost:5107/api/Employee/list'
  ]

  console.log('开始测试数据字典API端点...')

  for (const url of testUrls) {
    try {
      console.log(`测试: ${url}`)
      const response = await fetch(url + (url.includes('?') ? '&' : '?') + 'pageSize=10', {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`,
          'Content-Type': 'application/json'
        }
      })
      console.log(`${url} - 状态: ${response.status}`)

      if (response.ok) {
        const data = await response.json()
        console.log(`✅ ${url} - 成功响应:`, data)
        // 如果找到有效数据，标记为可用
        if (data.code === 200 && data.data && (Array.isArray(data.data) ? data.data.length > 0 : data.data.pageData?.length > 0)) {
          console.log(`🎯 找到可用API: ${url}`)
        }
      } else {
        console.log(`❌ ${url} - 错误: ${response.status} ${response.statusText}`)
      }
    } catch (error) {
      console.log(`❌ ${url} - 网络错误:`, error)
    }
  }
}

// 初始化基础数据字典（基于常见的业务数据）
const initializeBasicDataDictionaries = () => {
  // 仓库分类映射
  categoryMap.value.set(1, '原材料仓库')
  categoryMap.value.set(2, '成品仓库')
  categoryMap.value.set(3, '半成品仓库')
  categoryMap.value.set(4, '工具仓库')
  categoryMap.value.set(5, '备件仓库')

  // 存储类型映射
  storageTypeMap.value.set(1, '常温存储')
  storageTypeMap.value.set(2, '冷藏存储')
  storageTypeMap.value.set(3, '冷冻存储')
  storageTypeMap.value.set(4, '恒温存储')
  storageTypeMap.value.set(5, '防潮存储')

  // 仓库结构映射
  structureMap.value.set(1, '平面仓库')
  structureMap.value.set(2, '立体仓库')
  structureMap.value.set(3, '货架仓库')
  structureMap.value.set(4, '自动化仓库')
  structureMap.value.set(5, '露天仓库')

  // 人员映射
  personMap.value.set(1, '张三')
  personMap.value.set(2, '李四')
  personMap.value.set(3, '王五')
  personMap.value.set(4, '赵六')
  personMap.value.set(5, '钱七')

  console.log('基础数据字典初始化完成:', {
    categories: categoryMap.value.size,
    storageTypes: storageTypeMap.value.size,
    structures: structureMap.value.size,
    persons: personMap.value.size
  })
}

// 加载数据字典
const loadDataDictionaries = async () => {
  try {
    console.log('开始加载数据字典...')

    // 先测试API是否可用 - 暂时禁用测试，直接加载数据
    // await testDataDictionaryAPIs()

    try {
      // 尝试从API加载数据字典 - 使用不分页的API
      console.log('开始加载数据字典...')
      const [categoryRes, storageTypeRes, structureRes, personRes] = await Promise.all([
        getAllWarehouseCategories(),
        getAllStorageTypes(),
        getAllWarehouseStructures(),
        getAllPersons()
      ])
      console.log('数据字典API响应:', { categoryRes, storageTypeRes, structureRes, personRes })

      let hasApiData = false

      // 构建分类映射
      if (categoryRes.success) {
        const categories = categoryRes.data || []
        console.log('仓库分类数据:', categories)
        if (categories.length > 0) {
          categoryMap.value.clear()
          categories.forEach((item: any) => {
            categoryMap.value.set(item.id, item.categoryName || item.name)
          })
          hasApiData = true
          console.log('仓库分类映射构建完成:', categoryMap.value)
        }
      }

      // 构建存储类型映射
      if (storageTypeRes.success) {
        const storageTypes = storageTypeRes.data || []
        console.log('存储类型数据:', storageTypes)
        if (storageTypes.length > 0) {
          storageTypeMap.value.clear()
          storageTypes.forEach((item: any) => {
            storageTypeMap.value.set(item.id, item.typeName || item.name)
          })
          hasApiData = true
          console.log('存储类型映射构建完成:', storageTypeMap.value)
        }
      }

      // 构建仓库结构映射
      if (structureRes.success) {
        const structures = structureRes.data || []
        console.log('仓库结构数据:', structures)
        if (structures.length > 0) {
          structureMap.value.clear()
          structures.forEach((item: any) => {
            structureMap.value.set(item.id, item.structureName || item.name)
          })
          hasApiData = true
          console.log('仓库结构映射构建完成:', structureMap.value)
        }
      }

      // 构建人员映射
      if (personRes.success) {
        const persons = personRes.data || []
        console.log('人员数据:', persons)
        if (persons.length > 0) {
          personMap.value.clear()
          persons.forEach((item: any) => {
            personMap.value.set(item.id, item.personName || item.name || item.userName)
          })
          hasApiData = true
          console.log('人员映射构建完成:', personMap.value)
        }
      }

      if (!hasApiData) {
        console.log('API数据为空，使用基础数据字典')
        initializeBasicDataDictionaries()
      } else {
        console.log('API数据字典加载完成:', {
          categories: categoryMap.value.size,
          storageTypes: storageTypeMap.value.size,
          structures: structureMap.value.size,
          persons: personMap.value.size
        })

        // 数据字典加载完成后，如果已经有仓库数据，重新映射关联字段
        if (warehouseList.value.length > 0) {
          console.log('重新映射仓库数据的关联字段...')
          warehouseList.value = warehouseList.value.map((warehouse: any) => ({
            ...warehouse,
            categoryName: categoryMap.value.get(warehouse.categoryId) || warehouse.categoryName || '未分类',
            storageTypeName: storageTypeMap.value.get(warehouse.storageTypeId) || warehouse.storageTypeName || '未设置',
            structureName: structureMap.value.get(warehouse.structureId) || warehouse.structureName || '未设置',
            personInChargeName: personMap.value.get(warehouse.personInChargeId) || warehouse.personInChargeName || '未指定'
          }))
        }
      }
    } catch (apiError) {
      console.log('API加载失败，使用基础数据字典:', apiError)
      initializeBasicDataDictionaries()
    }
  } catch (error) {
    console.error('加载数据字典失败，使用基础数据字典:', error)
    initializeBasicDataDictionaries()
  }
}

const loadWarehouseList = async () => {
  try {
    loading.value = true
    const params: any = {
      Page: pagination.currentPage,
      PageSize: pagination.pageSize,
      Keyword: searchKeyword.value
    }

    console.log('开始加载仓库列表...')
    console.log('请求参数:', params)

    const response = await getWarehouseList(params)
    console.log('API响应完整数据:', JSON.stringify(response, null, 2))

    // 检查多种可能的成功响应格式
    if (response.success || response.code === 200 || response.Code === 200 || response.code === 'Success' || response.Code === 'Success') {
      // 根据后端APIPageing结构，数据在Data字段中
      let warehouses = response.data?.pageData || response.data?.PageData || response.data || []
      console.log('提取的仓库数据:', warehouses)

      // 使用数据字典填充关联字段
      warehouses = warehouses.map((warehouse: any) => {
        const categoryName = categoryMap.value.get(warehouse.categoryId) || warehouse.categoryName || '未分类'
        const storageTypeName = storageTypeMap.value.get(warehouse.storageTypeId) || warehouse.storageTypeName || '未设置'
        const structureName = structureMap.value.get(warehouse.structureId) || warehouse.structureName || '未设置'
        const personInChargeName = personMap.value.get(warehouse.personInChargeId) || warehouse.personInChargeName || '未指定'

        console.log(`仓库 ${warehouse.warehouseName} 字段映射:`, {
          categoryId: warehouse.categoryId,
          categoryName,
          storageTypeId: warehouse.storageTypeId,
          storageTypeName,
          structureId: warehouse.structureId,
          structureName,
          personInChargeId: warehouse.personInChargeId,
          personInChargeName
        })

        return {
          ...warehouse,
          categoryName,
          storageTypeName,
          structureName,
          personInChargeName
        }
      })

      warehouseList.value = warehouses
      pagination.total = response.data?.totalCount || response.data?.TotalCount || warehouses.length

      console.log('最终仓库列表数据:', warehouseList.value)
      console.log('总数:', pagination.total)
      console.log('数据字典状态:', {
        categories: categoryMap.value.size,
        storageTypes: storageTypeMap.value.size,
        structures: structureMap.value.size,
        persons: personMap.value.size
      })

      if (warehouses.length === 0) {
        console.warn('警告：API返回成功但数据为空')
        ElMessage.info('暂无仓库数据')
      } else {
        console.log(`成功加载 ${warehouses.length} 条仓库数据`)
      }
    } else {
      console.error('API返回错误:', response.message || response.Message)
      throw new Error(response.message || response.Message || '获取仓库列表失败')
    }
  } catch (error: unknown) {
    console.error('加载仓库列表失败:', error)
    const msg = getErrorMessage(error)

    // 尝试读取可能存在的响应信息
    const anyErr = error as any
    console.error('错误详情:', {
      message: msg,
      response: anyErr?.response,
      status: anyErr?.response?.status,
      data: anyErr?.response?.data
    })

    // 检查是否是认证问题
    if (anyErr?.response?.status === 401) {
      ElMessage.error('认证失败，请重新登录')
      console.log('当前token:', localStorage.getItem('token'))
    } else if (anyErr?.response?.status === 404) {
      ElMessage.error('API接口不存在，请检查后端服务')
    } else if (isNetworkError(error)) {
      ElMessage.error('网络连接失败，请检查后端服务是否启动')
    } else {
      ElMessage.error(`加载仓库列表失败: ${msg || '未知错误'}`)
    }

    // 设置空数据以显示"暂无数据"
    warehouseList.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadWarehouseList()
}



const handleAdd = () => {
  dialogMode.value = 'add'
  currentWarehouse.value = null
  dialogVisible.value = true
}

const handleEdit = async (row: any) => {
  try {
  // 如果是根节点，使用根节点编辑对话框
  if (row.warehouseNumber === '根节点') {
    currentWarehouse.value = { ...row }
    rootNodeDialogVisible.value = true
      return
    }

    loading.value = true
    console.log('开始获取仓库详情进行编辑:', row.id, row.warehouseName)
    
    // 获取完整的仓库详情数据
    const response = await getWarehouseById(row.id)
    console.log('仓库详情响应:', response)
    
    if (response.success || response.code === 200 || response.Code === 200 || response.code === 'Success' || response.Code === 'Success') {
      const warehouseDetail = response.data
      console.log('仓库详情数据:', warehouseDetail)
      
      // 规范化字段数据
      const normalized = {
        id: warehouseDetail.id ?? warehouseDetail.Id,
        warehouseNumber: warehouseDetail.warehouseNumber ?? warehouseDetail.WarehouseNumber,
        warehouseName: warehouseDetail.warehouseName ?? warehouseDetail.WarehouseName,
        parentId: warehouseDetail.parentId ?? warehouseDetail.ParentId,
        categoryId: warehouseDetail.categoryId ?? warehouseDetail.CategoryId,
        storageTypeId: warehouseDetail.storageTypeId ?? warehouseDetail.StorageTypeId,
        structureId: warehouseDetail.structureId ?? warehouseDetail.StructureId,
        personInChargeId: warehouseDetail.personInChargeId ?? warehouseDetail.PersonInChargeId,
        address: warehouseDetail.address ?? warehouseDetail.Address ?? '',
        remarks: warehouseDetail.remarks ?? warehouseDetail.Remarks ?? '',
        isEnabled: warehouseDetail.isEnabled ?? warehouseDetail.IsEnabled ?? true,
        // 保留显示用的名称字段
        categoryName: warehouseDetail.categoryName ?? warehouseDetail.CategoryName,
        storageTypeName: warehouseDetail.storageTypeName ?? warehouseDetail.StorageTypeName,
        structureName: warehouseDetail.structureName ?? warehouseDetail.StructureName,
        personInChargeName: warehouseDetail.personInChargeName ?? warehouseDetail.PersonInChargeName
      }
      
      console.log('规范化后的仓库数据:', normalized)
      
    dialogMode.value = 'edit'
      currentWarehouse.value = normalized
    dialogVisible.value = true
    } else {
      console.error('获取仓库详情失败:', response.message || response.Message)
      ElMessage.error(response.message || response.Message || '获取仓库详情失败')
    }
  } catch (error) {
    console.error('获取仓库详情失败:', error)
    const anyErr = error as any
    if (anyErr?.response?.status === 404) {
      ElMessage.error('仓库不存在或已被删除')
    } else {
      ElMessage.error('获取仓库详情失败，请检查网络连接')
    }
  } finally {
    loading.value = false
  }
}

const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除仓库"${row.warehouseName}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    console.log('开始删除仓库:', row.id, row.warehouseName)
    const response: any = await deleteWarehouse(row.id)
    console.log('删除API响应:', response)

    // 检查多种可能的成功响应格式
    if (response.success || response.code === 200 || response.Code === 200 || response.code === 'Success' || response.Code === 'Success') {
      ElMessage.success('删除成功')
      console.log('删除成功，开始刷新数据...')
      
      // 确保数据刷新成功
      try {
        await loadWarehouseList()
        console.log('数据刷新完成')
      } catch (refreshError) {
        console.error('数据刷新失败:', refreshError)
        ElMessage.warning('删除成功，但数据刷新失败，请手动刷新页面')
      }
    } else {
      console.error('删除失败，响应:', response)
      ElMessage.error(response.message || response.Message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除仓库失败:', error)
      
      // 检查是否是网络错误或其他可恢复的错误
      const anyErr = error as any
      if (anyErr?.response?.status === 404) {
        ElMessage.error('仓库不存在或已被删除')
        // 即使删除失败，也尝试刷新数据
        await loadWarehouseList()
      } else if (anyErr?.response?.status === 500) {
        ElMessage.error('服务器内部错误，请稍后重试')
      } else {
        ElMessage.error('删除仓库失败，请检查网络连接')
      }
    }
  }
}

const handleView = async (row: any) => {
  try {
    loading.value = true
    console.log('开始获取仓库详情进行查看:', row.id, row.warehouseName)
    
    // 获取完整的仓库详情数据
    const response = await getWarehouseById(row.id)
    console.log('仓库详情响应:', response)
    
    if (response.success || response.code === 200 || response.Code === 200 || response.code === 'Success' || response.Code === 'Success') {
      const warehouseDetail = response.data
      console.log('仓库详情数据:', warehouseDetail)
      
      // 规范化字段数据
      const normalized = {
        id: warehouseDetail.id ?? warehouseDetail.Id,
        warehouseNumber: warehouseDetail.warehouseNumber ?? warehouseDetail.WarehouseNumber,
        warehouseName: warehouseDetail.warehouseName ?? warehouseDetail.WarehouseName,
        parentId: warehouseDetail.parentId ?? warehouseDetail.ParentId,
        categoryId: warehouseDetail.categoryId ?? warehouseDetail.CategoryId,
        storageTypeId: warehouseDetail.storageTypeId ?? warehouseDetail.StorageTypeId,
        structureId: warehouseDetail.structureId ?? warehouseDetail.StructureId,
        personInChargeId: warehouseDetail.personInChargeId ?? warehouseDetail.PersonInChargeId,
        address: warehouseDetail.address ?? warehouseDetail.Address ?? '',
        remarks: warehouseDetail.remarks ?? warehouseDetail.Remarks ?? '',
        isEnabled: warehouseDetail.isEnabled ?? warehouseDetail.IsEnabled ?? true,
        createTime: warehouseDetail.createTime ?? warehouseDetail.CreateTime,
        createName: warehouseDetail.createName ?? warehouseDetail.CreateName,
        modifyTime: warehouseDetail.modifyTime ?? warehouseDetail.ModifyTime,
        modifierName: warehouseDetail.modifierName ?? warehouseDetail.ModifierName,
        // 保留显示用的名称字段
        categoryName: warehouseDetail.categoryName ?? warehouseDetail.CategoryName,
        storageTypeName: warehouseDetail.storageTypeName ?? warehouseDetail.StorageTypeName,
        structureName: warehouseDetail.structureName ?? warehouseDetail.StructureName,
        personInChargeName: warehouseDetail.personInChargeName ?? warehouseDetail.PersonInChargeName
      }
      
      console.log('规范化后的仓库详情数据:', normalized)
      
      currentWarehouse.value = normalized
  detailDialogVisible.value = true
    } else {
      console.error('获取仓库详情失败:', response.message || response.Message)
      ElMessage.error(response.message || response.Message || '获取仓库详情失败')
    }
  } catch (error) {
    console.error('获取仓库详情失败:', error)
    const anyErr = error as any
    if (anyErr?.response?.status === 404) {
      ElMessage.error('仓库不存在或已被删除')
    } else {
      ElMessage.error('获取仓库详情失败，请检查网络连接')
    }
  } finally {
    loading.value = false
  }
}

const handleExport = async () => {
  try {
    // 显示导出格式选择对话框
    ElMessageBox.confirm(
      '请选择导出格式',
      '导出选项',
      {
        confirmButtonText: 'Excel格式',
        cancelButtonText: 'CSV格式',
        distinguishCancelAndClose: true,
        type: 'info'
      }
    ).then(async () => {
      // 用户选择Excel格式
      await exportToExcel()
    }).catch((action) => {
      if (action === 'cancel') {
        // 用户选择CSV格式
        exportToCSV()
      }
    })
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请稍后重试')
  }
}

const exportToExcel = async () => {
  try {
    ElMessage.info('正在准备Excel导出数据...')
    
    // 获取所有仓库数据（不分页）
    const params = {
      page: 1,
      pageSize: 10000,
      keyword: searchKeyword.value
    }
    
    const response: any = await getWarehouseList(params)
    
    if (response.code === 200) {
      let warehouses = response.data?.pageData || []
      
      // 使用数据字典填充关联字段
      warehouses = warehouses.map((warehouse: any) => ({
        ...warehouse,
        categoryName: categoryMap.value.get(warehouse.categoryId) || warehouse.categoryName || '未分类',
        storageTypeName: storageTypeMap.value.get(warehouse.storageTypeId) || warehouse.storageTypeName || '未设置',
        structureName: structureMap.value.get(warehouse.structureId) || warehouse.structureName || '未设置',
        personInChargeName: personMap.value.get(warehouse.personInChargeId) || warehouse.personInChargeName || '未指定'
      }))
      
      // 准备导出数据
      const exportData = warehouses.map((warehouse: any, index: number) => ({
        '序号': index + 1,
        '仓库名称': warehouse.warehouseName || '',
        '仓库编号': warehouse.warehouseNumber || '',
        '仓库分类': warehouse.categoryName || '',
        '存储类型': warehouse.storageTypeName || '',
        '仓库结构': warehouse.structureName || '',
        '状态': warehouse.isEnabled ? '启用' : '禁用',
        '负责人': warehouse.personInChargeName || '',
        '仓库地址': warehouse.address || '',
        '备注': warehouse.remarks || '',
        '创建时间': warehouse.createTime ? new Date(warehouse.createTime).toLocaleString() : '',
        '更新时间': warehouse.updateTime ? new Date(warehouse.updateTime).toLocaleString() : ''
      }))
      
      // 创建工作簿
      const wb = XLSX.utils.book_new()
      const ws = XLSX.utils.json_to_sheet(exportData)
      
      // 设置列宽
      const colWidths = [
        { wch: 8 },   // 序号
        { wch: 20 },  // 仓库名称
        { wch: 15 },  // 仓库编号
        { wch: 12 },  // 仓库分类
        { wch: 12 },  // 存储类型
        { wch: 12 },  // 仓库结构
        { wch: 8 },   // 状态
        { wch: 10 },  // 负责人
        { wch: 30 },  // 仓库地址
        { wch: 20 },  // 备注
        { wch: 20 },  // 创建时间
        { wch: 20 }   // 更新时间
      ]
      ws['!cols'] = colWidths
      
      // 添加工作表到工作簿
      XLSX.utils.book_append_sheet(wb, ws, '仓库管理数据')
      
      // 生成Excel文件并下载
      const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
      const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
      saveAs(blob, `仓库管理数据_${new Date().toISOString().slice(0, 10)}.xlsx`)
      
      ElMessage.success(`成功导出 ${exportData.length} 条仓库数据到Excel`)
    } else {
      ElMessage.error('获取导出数据失败')
    }
  } catch (error) {
    console.error('Excel导出失败:', error)
    ElMessage.error('Excel导出失败，请稍后重试')
  }
}

const exportToCSV = async () => {
  try {
    ElMessage.info('正在准备CSV导出数据...')
    
    // 获取所有仓库数据（不分页）
    const params = {
      page: 1,
      pageSize: 10000,
      keyword: searchKeyword.value
    }
    
    const response: any = await getWarehouseList(params)
    
    if (response.code === 200) {
      let warehouses = response.data?.pageData || []
      
      // 使用数据字典填充关联字段
      warehouses = warehouses.map((warehouse: any) => ({
        ...warehouse,
        categoryName: categoryMap.value.get(warehouse.categoryId) || warehouse.categoryName || '未分类',
        storageTypeName: storageTypeMap.value.get(warehouse.storageTypeId) || warehouse.storageTypeName || '未设置',
        structureName: structureMap.value.get(warehouse.structureId) || warehouse.structureName || '未设置',
        personInChargeName: personMap.value.get(warehouse.personInChargeId) || warehouse.personInChargeName || '未指定'
      }))
      
      // 准备导出数据
      const exportData = warehouses.map((warehouse: any, index: number) => ({
        '序号': index + 1,
        '仓库名称': warehouse.warehouseName || '',
        '仓库编号': warehouse.warehouseNumber || '',
        '仓库分类': warehouse.categoryName || '',
        '存储类型': warehouse.storageTypeName || '',
        '仓库结构': warehouse.structureName || '',
        '状态': warehouse.isEnabled ? '启用' : '禁用',
        '负责人': warehouse.personInChargeName || '',
        '仓库地址': warehouse.address || '',
        '备注': warehouse.remarks || '',
        '创建时间': warehouse.createTime ? new Date(warehouse.createTime).toLocaleString() : '',
        '更新时间': warehouse.updateTime ? new Date(warehouse.updateTime).toLocaleString() : ''
      }))
      
      // 生成CSV内容
      const headers = Object.keys(exportData[0])
      const csvContent = [
        headers.join(','),
        ...exportData.map(row => headers.map(header => `"${row[header]}"`).join(','))
      ].join('\n')
      
      // 创建并下载文件
      const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' })
      const link = document.createElement('a')
      const url = URL.createObjectURL(blob)
      link.setAttribute('href', url)
      link.setAttribute('download', `仓库管理数据_${new Date().toISOString().slice(0, 10)}.csv`)
      link.style.visibility = 'hidden'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      ElMessage.success(`成功导出 ${exportData.length} 条仓库数据到CSV`)
    } else {
      ElMessage.error('获取导出数据失败')
    }
  } catch (error) {
    console.error('CSV导出失败:', error)
    ElMessage.error('CSV导出失败，请稍后重试')
  }
}

const toggleViewMode = () => {
  viewMode.value = viewMode.value === 'table' ? 'list' : 'table'
}

const handleDialogSuccess = () => {
  dialogVisible.value = false
  loadWarehouseList()
  ElMessage.success(dialogMode.value === 'add' ? '新增成功' : '编辑成功')
}

const handleRootNodeSuccess = () => {
  rootNodeDialogVisible.value = false
  loadWarehouseList()
  ElMessage.success('根节点更新成功')
}

const handleEditFromDetail = (warehouse: any) => {
  handleEdit(warehouse)
}

const handleDeleteFromDetail = (warehouse: any) => {
  handleDelete(warehouse)
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadWarehouseList()
}

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  loadWarehouseList()
}

// 刷新数据字典
const refreshDataDictionaries = async () => {
  try {
    console.log('手动刷新数据字典...')
    await loadDataDictionaries()

    // 重新加载仓库列表以应用新的数据字典
    await loadWarehouseList()
    ElMessage.success('数据字典刷新成功')
  } catch (error) {
    console.error('刷新数据字典失败:', error)
    ElMessage.error('刷新数据字典失败')
  }
}

// 测试不同端口和API路径
const testAllPorts = async () => {
  const testUrls = [
    'http://localhost:5000/api/Warehouse/list',
    'http://localhost:5000/api/Inbound/list'
  ]

  console.log('开始测试所有可能的API端点...')

  for (const url of testUrls) {
    try {
      console.log(`测试: ${url}`)
      const response = await fetch(url + '?page=1&pageSize=5', {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`,
          'Content-Type': 'application/json'
        }
      })
      console.log(`${url} - 状态: ${response.status}`)

      if (response.ok) {
        const data = await response.json()
        console.log(`${url} - 成功响应:`, data)
        ElMessage.success(`找到可用API: ${url}`)
      } else {
        console.log(`${url} - 错误: ${response.statusText}`)
      }
    } catch (error) {
      console.log(`${url} - 网络错误:`, error)
    }
  }
}





// 添加调试信息显示
const debugInfo = ref({
  apiStatus: '未测试',
  dataLoaded: false,
  errorMessage: ''
})

// 生命周期
onMounted(async () => {
  console.log('组件已挂载，开始加载数据...')
  debugInfo.value.apiStatus = '正在加载数据字典...'

  try {
    // 检查认证状态
    const token = localStorage.getItem('token')
    console.log('当前token:', token)

    // 先加载数据字典，再加载仓库列表
    console.log('开始加载数据字典...')
    debugInfo.value.apiStatus = '正在加载数据字典...'
    await loadDataDictionaries()

    console.log('数据字典加载完成，开始加载仓库列表...')
    debugInfo.value.apiStatus = '正在加载仓库列表...'
    await loadWarehouseList()
    debugInfo.value.dataLoaded = true
    debugInfo.value.apiStatus = '所有数据加载完成'
  } catch (error: unknown) {
    debugInfo.value.errorMessage = getErrorMessage(error) || '未知错误'
    debugInfo.value.apiStatus = '数据加载失败'
    console.error('数据加载失败:', error)
  }
})
</script>

<style scoped>
.warehouse-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.left-operations {
  display: flex;
  gap: 12px;
}

.right-operations {
  display: flex;
  align-items: center;
  gap: 12px;
}

.search-input {
  width: 300px;
}

.view-toggle {
  padding: 8px 12px;
}

.warehouse-list {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.warehouse-table {
  width: 100%;
}

.warehouse-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-button--link) {
  padding: 4px 8px;
  font-size: 14px;
}
</style>